//
//  Moya.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/26.
//

import Foundation
import Moya
enum EPApi{
    //MARK: - 用户模块
    case checkUpdate(_ productNumber:String, _ firmwareVersionCode:String)
    case download(_ file:String)
    
    // 获取想要存储的文件路径
     var localLocation: URL {
         switch self {
         case .download(let fileName):
             let filePath = FileManager.default.temporaryDirectory
             return filePath.appendingPathComponent(fileName)
         default:
             return URL(fileURLWithPath: "")
         }
     }
     // 封装下下载路径
     var downloadDestination: DownloadDestination {
         // `createIntermediateDirectories` will create directories in file path
         return { _, _ in return (self.localLocation, [.removePreviousFile, .createIntermediateDirectories]) }
     }
}

extension EPApi:TargetType{
    ///baseurl
    var baseURL: URL{
        switch self{
        case .download:
            return URL(string: "http://wuquedistribution.com:12348")!
        default:
            return URL(string: "https://wuquedistribution.com:12349")!
        }
    }
    ///公共请求头
    var headers: [String : String]? {
        return ["Content-type":"application/json"]
    }
    ///请求api的路径
    var path: String {
        switch self{
        case .checkUpdate:///检查固件更新
            return "/checkUpdate"
        case let .download(file):
            return "/firmware/download/"+file
        }
    }
    
    /// 请求方式
    var method: Moya.Method {
        switch self{
            //MARK: - 用户模块
        case .checkUpdate:///app密码登录
            return .get
        case .download:
            return .get
        }
    }
    /// 解析格式
    var sampleData: Data{
        return "{}".data(using: String.Encoding.utf8)!
        //return Data(base64Encoded: "just for test")!
    }
    
    
    var task: Task {
        switch self{
        case let.checkUpdate(produce, version):///App用户退出登录
            return .requestParameters(parameters: ["productNumber":produce,"firmwareVersionCode":version], encoding: URLEncoding.default)
        case .download:
            return .downloadDestination(downloadDestination)
        }
    }
}


//插件写法
class loadingPlugin:PluginType{
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        return request
    }
    func willSend(_ request: RequestType, target: TargetType) {
    }
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
    }
    
    func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
        // 在这里对请求进行统一处理（比如有加密，可以统一进行解密）
        //        if let value = result.value, let _ = try? JSONSerialization.jsonObject(with: value.data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] {
        //
        //            let ob = ["code": 666, "description": "牛逼大发了"] as [String : Any]
        //            let data = try! JSONSerialization.data(withJSONObject: ob, options: JSONSerialization.WritingOptions.fragmentsAllowed)
        //
        //            let response = Response(statusCode: value.statusCode, data: data, request: value.request, response: value.response)
        //
        //            let res = Result<Response, MoyaError>.init(value: response)
        //            return res
        //        }
        return result
    }
    
}


